package com.mo.json;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.serializer.*;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;

/**
 * @author moon.pan
 * @program mo-all
 * @apiNote
 * @since 2022/3/28
 */
public class FastStudentSerializer implements ObjectSerializer {
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeConfig mapping = new SerializeConfig();
        // 设置对象序列化
        JSONSerializer jsonSerializer = new JSONSerializer(serializer.getWriter(), mapping);

        mapping.put(Double.class, new DoubleSerializer("0.00"));
        mapping.put(BigDecimal.class, new BigDecimalSerializer(value -> NumberUtil.round(value, 2)));
        SerializeWriter out = jsonSerializer.getWriter();
        // 添加值序列化
        jsonSerializer.addFilter((ValueFilter) (target, name, value) -> {

            if (value instanceof Double) {
                return NumberUtil.round((Double) value, 2);
            }

            if (value instanceof BigDecimal) {
                return NumberUtil.round((BigDecimal) value, 2);
            }

            return value;
        });

        if (object == null) {
            out.writeNull();
        } else {
            // 对象序列化
            Class<?> targetClass = object.getClass();
            JavaBeanSerializer javaBeanSerializer = new JavaBeanSerializer(targetClass);
            javaBeanSerializer.write(jsonSerializer, object, fieldName, fieldType, features);
        }
    }
}
